package org.szrcb.temu.SalesManage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.szrcb.temu.SalesManage.Vo.ResultVO;
import org.szrcb.temu.SalesManage.po.DeductResult;
import org.szrcb.temu.SalesManage.po.DeductPo;
import org.szrcb.temu.SalesManage.po.subOrder;
import org.szrcb.temu.SalesManage.pojo.Deduct;
import org.szrcb.temu.SalesManage.req.DeductReq;
import org.szrcb.temu.SalesManage.service.UserInfoService;
import org.szrcb.temu.SalesManage.utils.ResultVOUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DeductController {
    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/queryDeductList")
    public ResultVO<List<Deduct>> queryDeductList(@RequestHeader("access_token") String token, @RequestParam("dataTime") String dataTime, @RequestParam("mallId") String mallId, @RequestParam(value = "remark", required = false) String remark) throws ParseException {
        List<Deduct> deductList = new ArrayList<Deduct>();
        try {
            String cookie = "";
            if (token != null && !"".equals(token.trim())) {
                cookie = userInfoService.queryUserCookie(token);
                if ("".equals(cookie.trim())) {
                    return ResultVOUtil.error(1, "token不正确,请先登录Temu后台");
                }
            }

            int pageNo = 1;
            int pageSize = 100;
            DeductReq deductReq = new DeductReq();
            deductReq.setPageNum(1);
            deductReq.setPageSize(pageSize);

            ArrayList<Integer> fundTypeList = new ArrayList<>();
            fundTypeList.add(400);
            deductReq.setFundType(fundTypeList);

            //计算起始和结束日期
            String[] dataTimeArray = dataTime.trim().split("~");
            String beginDateContent = dataTimeArray[0];
            String endDateContent = dataTimeArray[1];

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date beginDate = formatter.parse(beginDateContent);
            Date endDate = formatter.parse(endDateContent);

            deductReq.setBeginTime(beginDate.getTime());
            deductReq.setEndTime(endDate.getTime());


            List<DeductPo> resultList = new ArrayList<DeductPo>();

            DeductResult deductResult = getDeductResult(cookie, mallId, deductReq);

            if (deductResult.getResultList() != null && deductResult.getResultList().size() > 0) {
                resultList.addAll(filterDeductPo(deductResult.getResultList(), remark));
            }

            Integer total = deductResult.getTotal();
            //计算页数，查询
            int totalPages = (int) Math.ceil((double) total / pageSize); // 总页数，使用Math.ceil向上取整
            if (totalPages > 1) {
                for (int i = pageNo + 1; i <= totalPages; i++) {
                    deductReq.setPageNum(i);
                    deductResult = getDeductResult(cookie, mallId, deductReq);

                    List<DeductPo> results = deductResult.getResultList();
                    if (results != null && results.size() > 0) {
                        resultList.addAll(filterDeductPo(results, remark));
                    }
                }
            }

            if (resultList != null && resultList.size() > 0) {
                resultList.forEach(deductPo -> {
                    Deduct deduct = new Deduct();
                    deduct.setCreateTime(deductPo.getCreateTime());
                    deduct.setTransactionTime(deductPo.getTransactionTime());
                    deduct.setSymbol(deductPo.getAmountFormat().getSymbol());
                    deduct.setDigitalText(deductPo.getAmountFormat().getDigitalText());
                    deduct.setBizType(deductPo.getBizType());
                    deduct.setRemark(deductPo.getRemark());
                    deductList.add(deduct);
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultVOUtil.success(deductList);
    }

    private List<DeductPo> filterDeductPo(List<DeductPo> results, String remark) {
        if ((remark != null && remark.trim() != "")) {
            List<DeductPo> collect = results.stream().filter(deductPo ->
                    deductPo.getRemark().contains(remark)
            ).collect(Collectors.toList());
            return collect;
        }
        return results;
    }

    private DeductResult getDeductResult(String cookie, String mallId, DeductReq req) {
        JSONObject deductResultObject = null;
        boolean deductBoolean = false;
        //循环请求数据,直到请求成功，获取到第一页扣款数据
        while (!deductBoolean) {
            deductResultObject = getDeductInfoJson("https://seller.kuajingmaihuo.com/api/merchant/fund/detail/pageSearch", mallId, cookie, req);
            deductBoolean = deductResultObject.getObject("success", boolean.class);
        }
        return deductResultObject.getObject("result", DeductResult.class);
    }

    private JSONObject getDeductInfoJson(String httpUrl, String mallId, String cookie, DeductReq req) {
        StringBuilder content = new StringBuilder();
        HttpURLConnection conn = null;
        BufferedReader br = null;
        try {
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Origin", "https://seller.kuajingmaihuo.com");
            conn.setRequestProperty("cookie", cookie);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("MallId", mallId);
            conn.setDoOutput(true);

            String deductReqJson = JSON.toJSONString(req);

            try (OutputStream os = conn.getOutputStream()) {
                os.write(deductReqJson.getBytes());
            }

            conn.connect();

            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;

            while ((inputLine = br.readLine()) != null) {
                content.append(inputLine);
            }
            br.close();
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return JSONObject.parseObject(content.toString());
    }
}
